import axios from 'axios'
import { requestErrorStore } from '@/store/request'
import { showToast, showLoadingToast, closeToast } from 'vant'

const requestError = requestErrorStore()
const instance = axios.create({
    baseURL: import.meta.env.VITE_BASE_API,
    timeout: 50000
})


//请求拦截器
instance.interceptors.request.use(
    config => {
        if (localStorage.getItem('token')) {
            config.headers.Authorization = localStorage.getItem('token')
        }
        showLoadingToast({
            duration: 0,
            message: '加载中...',
            forbidClick: true,
            loadingType: 'spinner'
        })
        return config
    },
    err => {
        closeToast()
        return Promise.reject(err)
    }
)

// 响应拦截器
instance.interceptors.response.use(
    res => {
        requestError.updateLoading(false)
        closeToast()
        const { code, msg } = res.data
        if (code != 0) {
            showToast(msg)
            return
        }
        return res.data
    },
    err => {
        showToast('系统出错')
        closeToast()
        requestError.updateLoading(false)
        requestError.updateError(true)
        return Promise.reject(err)
    }
)

export default instance